<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>技术码六甲</title>
  <style>
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
    }

    body {
        background: #171717;
        color: #fff;
        height: 100vh;
        display: flex;
        flex-direction: column;
    }

    .container {
        max-width: 800px;
        margin: 0 auto;
        width: 100%;
        height: 100%;
        padding: 20px;
        display: flex;
        flex-direction: column;
    }

    .chat-container {
        flex: 1;
        overflow-y: auto;
        padding: 20px 0;
        scroll-behavior: smooth;
    }

    .message {
        display: flex;
        gap: 15px;
        margin-bottom: 30px;
    }

    .user-message {
        flex-direction: row-reverse;
    }

    .avatar {
        width: 40px;
        height: 40px;
        border-radius: 6px;
        background: #2E2E2E;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .user-avatar {
        background: #157EFB;
    }

    .content {
        max-width: 85%;
        padding: 15px 20px;
        border-radius: 12px;
        line-height: 1.6;
    }

    .assistant-content {
        background: #2E2E2E;
        border-radius: 12px 12px 12px 4px;
    }

    .user-content {
        background: #157EFB;
        border-radius: 12px 12px 4px 12px;
    }

    .input-container {
        position: relative;
        padding: 20px 0;
        border-top: 1px solid #2E2E2E;
    }

    .input-wrapper {
        display: flex;
        gap: 10px;
        background: #2E2E2E;
        border-radius: 12px;
        padding: 8px;
    }

    #messageInput {
        flex: 1;
        background: transparent;
        border: none;
        color: #fff;
        padding: 12px;
        font-size: 16px;
        outline: none;
    }

    #sendButton {
        background: #157EFB;
        border: none;
        color: white;
        padding: 12px 24px;
        border-radius: 8px;
        cursor: pointer;
        transition: opacity 0.2s;
    }

    #sendButton:hover {
        opacity: 0.9;
    }

    #sendButton:disabled {
        background: #666;
        cursor: not-allowed;
    }

    .loading-dots {
        display: none;
        padding: 15px 20px;
    }

    .loading-dots span {
        animation: blink 1.4s infinite both;
        margin-right: 4px;
    }

    .loading-dots span:nth-child(2) {
        animation-delay: 0.2s;
    }

    .loading-dots span:nth-child(3) {
        animation-delay: 0.4s;
    }

    @keyframes blink {
        0%, 100% { opacity: 0.2; }
        20% { opacity: 1; }
    }
  </style>
</head>
<body>
<div class="container">
  <div class="chat-container" id="chatContainer">
    <!-- 示例消息 -->
    <div class="message">
      <div class="avatar">AI</div>
      <div class="content assitant-content">您好！我是DeepSeek，有什么可以帮您？</div>
    </div>
  </div>

  <div class="input-container">
    <div class="input-wrapper">
      <input type="text" id="messageInput" placeholder="输入消息..." />
      <button id="sendButton" onclick="sendMessage()">发送</button>
    </div>
    <div class="loading-dots" id="loading">
      <span>.</span><span>.</span><span>.</span>
    </div>
  </div>
</div>

<script>
  const chatContainer = document.getElementById('chatContainer');
  const messageInput = document.getElementById('messageInput');
  const sendButton = document.getElementById('sendButton');
  const loading = document.getElementById('loading');

  // 处理Enter键发送
  messageInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter' && !e.shiftKey) {
          e.preventDefault();
          sendMessage();
      }
  });

  // 新增流式处理逻辑
  async function sendMessage() {
      const message = messageInput.value.trim();
      if (!message || sendButton.disabled) return;

      addMessage(message, 'user');
      messageInput.value = '';
      sendButton.disabled = true;
      loading.style.display = 'block';

      // 创建AI消息容器
      const aiMessage = createAIMessageContainer();

      try {
          const response = await fetch('/api/streamchat', {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/json'
              },
              body: JSON.stringify({ message })
          });

          const reader = response.body.getReader();
          const decoder = new TextDecoder();
          let buffer = '';

          loading.style.display = 'none'; // 隐藏加载动画

          while (true) {
              const { done, value } = await reader.read();
              if (done) break;

              buffer = decoder.decode(value, { stream: true });

              try {
                  //const data = JSON.parse(buffer);
                  aiMessage.textContent += buffer;
                  aiMessage.scrollIntoView();
              } catch (e) {
                  console.warn('解析JSON失败:', buffer);
              }
          }

          // 处理剩余缓冲区内容
          if (buffer) {
              try {
                  //const data = JSON.parse(buffer);
                  //aiMessage.textContent += data.content;
                  aiMessage.textContent += buffer;
              } catch (e) {
                  console.warn('解析剩余内容失败:', buffer);
              }
          }

      } catch (error) {
          console.error('Error:', error);
          aiMessage.textContent = '请求出错，请稍后再试';
      } finally {
          sendButton.disabled = false;
          loading.style.display = 'none';
      }
  }

  // 创建AI消息容器
  function createAIMessageContainer() {
      const messageDiv = document.createElement('div');
      messageDiv.className = 'message assistant-message';

      const avatar = document.createElement('div');
      avatar.className = 'avatar assistant-avatar';
      avatar.textContent = 'AI';

      const contentDiv = document.createElement('div');
      contentDiv.className = 'content assistant-content';

      messageDiv.appendChild(avatar);
      messageDiv.appendChild(contentDiv);
      chatContainer.appendChild(messageDiv);

      // 初始滚动
      chatContainer.scrollTop = chatContainer.scrollHeight;

      return contentDiv;
  }


  function addMessage(content, role) {
      const messageDiv = document.createElement('div');
      messageDiv.className = `message ${role}-message`;

      const avatar = document.createElement('div');
      avatar.className = `avatar ${role}-avatar`;
      avatar.textContent = role === 'user' ? 'ME' : 'AI';

      const contentDiv = document.createElement('div');
      contentDiv.className = `content ${role}-content`;
      contentDiv.textContent = content;

      messageDiv.appendChild(avatar);
      messageDiv.appendChild(contentDiv);
      chatContainer.appendChild(messageDiv);

      // 滚动到底部
      chatContainer.scrollTop = chatContainer.scrollHeight;
  }


  async function sendMessage1() {
      const message = messageInput.value.trim();
      if (!message || sendButton.disabled) return;

      // 添加用户消息
      addMessage(message, 'user');
      messageInput.value = '';
      sendButton.disabled = true;
      loading.style.display = 'block';

      try {
          // 调用后端API（根据你的实际接口修改）
          const response = await fetch('/api/streamchat?message='+message, {
              method: 'GET',
              headers: {
                  'Content-Type': 'application/json'
              }
              //body: message
          });

          if (!response.ok) throw new Error('请求失败');

          //const data = await response.json();
          //addMessage(data.textResponse, 'assistant');
          const data = await response.text();
          addMessage(data, 'assistant');
      } catch (error) {
          console.error('Error:', error);
          addMessage('请求出错，请稍后再试', 'assistant');
      } finally {
          sendButton.disabled = false;
          loading.style.display = 'none';
      }
  }

</script>
</body>
</html>